var prefix = jsctx + "/elecPile";

var pile = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/exportPile", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                stationName: $("#stationName").val().trim(),
                epNo: $("#epNo").val().trim(),
                elecStationId: $("#elecStationId").val(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPagePile",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    cache: false,
                    pageSize: 10,
                    pageList: [10, 20, 30],
                    // pageList: [10],
                    pageNumber: 1,
                    sidePagination: "server",
                    paginationShowPageGo: true,
                    height: h,
                    rightFixedColumns: true,
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            pileSort: $("#pileSort").val().trim(),
                            stationName: $("#stationName").val().trim(),
                            epNo: $("#epNo").val().trim(),
                            elecStationId: $("#elecStationId").val().trim()

                        };
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'pileNo', title: '电桩编号', align: 'center', width: '100'},
                        {field: 'pileSort', title: '桩体短号（显示号）', align: 'center', width: '100'},
                        {
                            field: 'pileElecType', title: '充电类型', align: 'center', width: '100',
                            formatter: function (value, row, index) {
                                if (value == '6') {
                                    return '<span>快充</span>';
                                } else if (value == '7') {
                                    return '<span>慢充</span>';
                                } else {
                                    return '-';
                                }
                            }
                        },
                        {
                            field: 'operateStatus', title: '投运状态', align: 'center', width: '100',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span>未上线</span>';
                                } else if (value == '1') {
                                    return '<span>上线</span>';
                                } else if (value == '2') {
                                    return '<span>下线</span>';
                                } else if (value == '3') {
                                    return '<span>故障</span>';
                                }
                            }
                        },
                        {field: 'equipmentModel', title: '电桩型号', align: 'center', width: '100'},
                        {
                            field: 'power', title: '额定输出功率', align: 'center', width: '100',
                            formatter: function (value, row, index) {
                                return '<span>' + value + 'kw</span>';
                            }
                        },
                        {field: 'hlhtManufacturerName', title: '生产厂商', align: 'center', width: '100'},
                        {field: 'hlhtManufacturerId', title: '出厂编号', align: 'center', width: '100'},
                        {field: 'productionDate', title: '生产日期', align: 'center', width: '100'},
                        {
                            field: 'gunNum', title: '充电枪数量', width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                return '<a helf="javascipt:void(0)" style="color:#06F !important" onclick="pile.gunListPage(\''
                                    + row.elecPileId
                                    + '\')">' + value + '</a>'
                            }
                        },
                        {field: 'stationName', title: '所属站点', width: '100', align: 'center'},
                        {field: 'operatorName', title: '所属加盟商', align: 'center', width: '100'},
                        {field: 'remark', title: '备注', align: 'center', width: '100'},
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '200',
                            align: 'center',
                            class: 'operate-td',
                            formatter: function (value, row, index) {
                                var a = '';
                                var b = '';
                                var c = '';
                                var d = '';
                                var e = '';
                                var q = '';
                                if (StationManager_pile_look) {
                                    d = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="桩列表" onclick="pile.detailElecPile(\''
                                        + row.elecPileId
                                        + '\')">详情</a> ';
                                }
                                if (StationManager_pile_update) {
                                    a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="桩列表" onclick="pile.gunListPage(\''
                                        + row.elecPileId
                                        + '\')">枪列表</a> ';
                                    b = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="桩列表" onclick="pile.editElecPile(\''
                                        + row.elecPileId
                                        + '\')">编辑桩</a> ';
                                    if (row.operateStatus == '0' || row.operateStatus == '2') {
                                        c = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="桩列表" onclick="pile.changeStatus(\''
                                            + row.elecPileId
                                            + '\')">上线</a> ';
                                    } else if (row.operateStatus == '1') {
                                        c = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="桩列表" onclick="pile.changeStatus(\''
                                            + row.elecPileId
                                            + '\')">下线</a> ';
                                    }
                                    e = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="桩列表" onclick="pile.deleteElecPile(\''
                                        + row.elecPileId
                                        + '\')">删除</a> ';
                                }
                                // return d + a + b + c + e;
                                return d + b + c + e;
                            }
                        }
                    ]
                });
    }

    function reLoad() {
        $(".fixed-table-header-columns").css("display", "none");
        $(".fixed-table-body-columns").css("display", "none");
        $('#exampleTable').bootstrapTable('refresh');
    }

    function addElecPileByStation(elecStationId) {
        location.href = jsctx + "/elecStation/addElecPileByStation/" + elecStationId;
    }

    function addElecPile() {
        location.href = prefix + "/addElecPile";
    }

    function editElecPile(elecPileId) {
        location.href = prefix + "/editElecPile/" + elecPileId;
    }

    function detailElecPile(elecPileId) {
        location.href = prefix + "/detailElecPile/" + elecPileId;
    }

    function gunListPage(elecPileId) {
        location.href = prefix + "/elecGun/" + elecPileId;
    }

    function pileFailure() {
        location.href = prefix + "/pileFailure";
    }

    function deleteElecPile(elecPileId) {
        layer.confirm('确定要删除选中的记录(对应枪同时被删除)？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteElecPile",
                type: "post",
                data: {
                    'elecPileId': elecPileId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function getArea() {
        var cityId = $("#cityId").val().trim();
        if (cityId == null || cityId == '') {
            $("#area").html("");
            var str = "<option value=''>行政区域</option>";
            $("#area").append(str);
        } else {
            $.ajax({
                url: prefix + "/getArea",
                type: "GET",
                data: {
                    cityId: cityId
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    $("#areaId").html("");
                    var str = "<option value=''>--请选择--</option>";
                    if (data.status == 200) {
                        $.each(data.data, function (i, item) {
                            str += "<option value=" + item.areaId + ">" + item.areaName + "</option>";
                        })
                        $("#areaId").append(str);
                    } else {
                        // parent.layer.msg(data.message);
                        $("#areaId").val("");
                    }
                }
            });
        }

    }

    function getCity() {
        var provinceId = $("#provinceId").val().trim();
        if (provinceId == null || provinceId == '') {
            $("#city").html("");
            var str = "<option>市区</option>";
            $("#city").append(str);
        } else {
            $.ajax({
                url: prefix + "/getCity",
                type: "GET",
                data: {
                    provinceId: provinceId
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    $("#cityId").html("");
                    var str = "<option value=''>--请选择--</option>";
                    if (data.status == 200) {
                        $.each(data.data, function (i, item) {
                            str += "<option value=" + item.cityId + ">" + item.cityName + "</option>";
                        })
                        $("#cityId").append(str);
                    } else {
                        // parent.layer.msg(data.message);
                        $("#cityId").val("");
                    }
                }
            });
        }

    }

    function goBack() {
        window.history.back();
    }

    function changeStatus(elecPileId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'elecPileId': elecPileId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }


    function printElecGunQrCode(gunNo) {
        layer.open({
            type: 2,
            title: '枪号：' + gunNo,
            shadeClose: false,
            area: ['400px', '350px'],
            content: prefix + '/genElecGunQrCode/' + gunNo,
            //弹窗下方的按钮
            // btn: ['下载'],
            // //绑定第一个按钮的点击事件
            // btn1: function (gunNo) {
            //     genElecGunQrCodeUrl(gunNo)
            //     var url = document.getElementById("qrcode").childNodes[0].toDataURL("image/png");
            //     //下载图片到本地
            //     var a = document.createElement('a');
            //     var event = new MouseEvent('click');
            //     a.download = gunNo;
            //     a.href = url;
            //     a.dispatchEvent(event);
            // }
        });
    }

    function genElecGunQrCodeUrl(gunNo) {
        $.ajax({
            url: prefix + "/genElecGunQrCodeUrl",
            type: "GET",
            data: {
                'gunNo': gunNo
            },
            success: function (data) {
                if (data.status == 200) {
                    var qrcode = new QRCode(document.getElementById("qrcode"), {width: 150, height: 150});
                    qrcode.clear();
                    qrcode.makeCode(data.data);
                } else {
                    layer.msg("下载失败");
                }
            }
        });
    }

    function editElecGun(elecGunId) {
        location.href = prefix + "/editElecGun/" + elecGunId;
    }

    function updateGunStatus(elecGunId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateGunStatus",
                type: "post",
                data: {
                    'elecGunId': elecGunId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function sendUnlock(elecGunId) {
        layer.confirm('确定解锁此枪？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/sendUnlock",
                type: "post",
                data: {
                    'elecGunId': elecGunId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("解锁成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        addElecPile: addElecPile,
        gunListPage: gunListPage,
        changeStatus: changeStatus,
        deleteElecPile: deleteElecPile,
        editElecPile: editElecPile,
        detailElecPile: detailElecPile,
        getArea: getArea,
        getCity: getCity,
        addElecPileByStation: addElecPileByStation,
        printElecGunQrCode: printElecGunQrCode,
        editElecGun: editElecGun,
        updateGunStatus: updateGunStatus,
        sendUnlock: sendUnlock,
        exportList: exportList,
        pileFailure: pileFailure
    };
})();

var addElecPile = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function save() {
        if (isajaxsend) {
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateElecPile",
                data: $('#addElecPile').serialize(),
                async: false,
                beforeSend: function () {
                    isajaxsend = false;
                },
                success: function (data) {
                    if (data.status == 200) {
                        isajaxsend = false;
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        isajaxsend = true;
                        parent.layer.alert(data.message)
                    }

                },
                error: function (request) {
                    isajaxsend = true;
                    parent.layer.alert("Connection error");
                },
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#addElecPile").validate({
            rules: {
                pileSort: {
                    required: true
                },
                elecStationId: {
                    required: true
                },
                equipmentModel: {
                    required: true
                },

                pileType: {
                    required: true
                }

            },
            messages: {
                pileSort: {
                    required: icon + "请输入桩体短号"
                },
                elecStationId: {
                    required: icon + "请选择充电站名称"
                },
                equipmentModel: {
                    required: icon + "请输入设备型号"
                },
                power: {
                    required: icon + "请输入额定功率",
                    number: icon + "请输入有效数字",
                    maxlength: icon + "最大长度为5",
                },
                pileType: {
                    required: icon + "请选择设备类型"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();
